<style>
.container {
  padding-top: 15px;
  min-height: 600px;
  max-height: 900px;
}
.pl-58 {
  padding-left: 58px;
}
.w-168 {
  width: 168px;
}
.w-40 {
  width: 40%;
}
</style>
<template>
  <el-row class="container bg-white">
    <el-col :span="24">
      <el-row
        type="flex"
        class="toolbar"
        justify="center">
        <el-col :span="23">
          <el-row
            type="flex"
            justify="space-between">
            <el-col :span="4">
              <el-button @click="addRow()">新增</el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row
        type="flex"
        class="table"
        justify="center">
        <el-col :span="23">
          <el-table
            :data="tableData"
            style="width: 100%"
            height="740">
            <el-table-column
              label="操作"
              fixed>
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="editRow(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  :disabled="(!scope.row.category) && (!scope.row.orderServiceType)"
                  size="mini"
                  type="danger"
                  @click="deleteRow(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column
              fixed
              prop="orderServiceType"
              label="服务类型">
              <template slot-scope="scope">{{ scope.row.orderServiceType?scope.row.orderServiceType:'全部' }}</template>
            </el-table-column>
            <el-table-column
              prop="categoryNames"
              label="服务品类" />
            <el-table-column
              prop="optionalLabel"
              label="选填项目" />
            <el-table-column
              prop="requiredLabel"
              label="必填项目" />
            <el-table-column
              prop="photoNumber"
              label="图片数量"
              width="100" />
            <el-table-column
              prop="photoDesc"
              label="图片说明" />
          </el-table>
        </el-col>
      </el-row>
      <el-dialog
        :center="true"
        :fullscreen="true"
        :title="fromTitle"
        :visible.sync="completionFormVisible"
        width="60%">
        <el-form :model="completion">
          <el-form-item
            :label-width="formLabelWidth"
            label="服务类型">
            <el-checkbox-group
              v-model="completion.orderServiceType"
              size="medium">
              <el-checkbox
                label="维修"
                border />
              <el-checkbox
                label="安装"
                border />
              <el-checkbox
                label="保养"
                border />
              <el-checkbox
                label="移机"
                border />
              <el-checkbox
                label="清洗"
                border />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item
            :label-width="formLabelWidth"
            label="服务品类">
            <el-checkbox-group
              v-model="completion.category"
              size="medium"
              class="pl-58">
              <el-checkbox
                v-for="item in categoryOptions"
                :label="item.categoryName"
                :key="item.categoryId"
                class="w-168"
                border />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item
            :label-width="formLabelWidth"
            label="完工项目">
            <el-transfer
              v-model="completion.optionalItems"
              :left-default-checked="[2, 3]"
              :right-default-checked="[1]"
              :titles="['可选项目', '选填项目']"
              :button-texts="['', '']"
              :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
              }"
              :data="transferData"
              style="text-align: left; display: inline-block"
              filterable
              @change="optionalTransferChange">
              <span slot-scope="{ option }">{{ option.label }}</span>
            </el-transfer>
            <el-transfer
              v-model="completion.requiredItems"
              :left-default-checked="[2, 3]"
              :right-default-checked="[1]"
              :titles="['可选项目', '必填项目']"
              :button-texts="['', '']"
              :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
              }"
              :data="transferData"
              style="text-align: left; display: inline-block"
              class="pl-10"
              filterable
              @change="requiredTransferChange">
              <span slot-scope="{ option }">{{ option.label }}</span>
            </el-transfer>
          </el-form-item>
          <el-form-item
            :label-width="formLabelWidth"
            label="照片数量">
            <el-input-number
              v-model="completion.photoNumber"
              :controls="false"
              :min="1"
              :max="10" />
          </el-form-item>
          <el-form-item
            :label-width="formLabelWidth"
            label="照片描述">
            <el-input
              :rows="2"
              v-model="completion.photoDesc"
              type="textarea"
              class="w-40"
              placeholder="请输入内容" />
          </el-form-item>
        </el-form>
        <div
          slot="footer"
          class="dialog-footer">
          <el-button @click="completionFormVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitForm()">确 定</el-button>
        </div>
      </el-dialog>
    </el-col>
  </el-row>
</template>

<script>
import { getCompletionCol } from '@/api/param'
import {
  getCompletionPageList,
  getCompletion,
  removeCompletion,
  saveCompletion
} from '@/api/completion'
import { listPartnerCategory } from '@/api/category'
export default {
  data() {
    return {
      fromTitle: '',
      formLabelWidth: '680',
      completionId: '',
      completion: {
        completionId: '',
        partnerId: '',
        orderServiceType: [],
        category: [],
        optionalItems: [],
        requiredItems: [],
        photoNumber: 0,
        photoDesc: ''
      },
      completionFormVisible: false,
      transferData: [],
      categoryOptions: [],
      query: {
        partnerId: '',
        categoryId: '',
        orderServiceType: ''
      },
      tableData: []
    }
  },
  computed: {},
  watch: {},
  created() {
    const self = this
    self.query.partnerId = self.$route.query.partnerId
    self.completion.partnerId = self.$route.query.partnerId
    // self.loadPartnerOptions()
    self.loadCategoryOptions()
    self.loadTableData()
    // self.loadSpecificationOptions()
  },
  methods: {
    loadTableData() {
      const self = this
      getCompletionPageList(self.query)
        .then(response => {
          if (response.data.status === 'success') {
            self.tableData = response.data.data
          } else {
            self.$message({
              message: '完工项目加载失败' + response.data.messge,
              type: 'warning'
            })
          }
        })
        .catch(() => {
          self.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
    },
    loadCategoryOptions() {
      var self = this
      self.categoryOptions = []
      var data = { partnerId: self.query.partnerId }
      listPartnerCategory(data)
        .then(response => {
          if (response.data.status === 'success') {
            this.categoryOptions = response.data.data
          } else {
            this.$message({
              message: '品类加载失败' + response.data.messge,
              type: 'warning'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
    },
    loadCompletionCol() {
      var self = this
      getCompletionCol()
        .then(response => {
          if (response.data.status === 'success') {
            self.transferData = response.data.data ? response.data.data : []
          } else {
            self.$message({
              message: '完工列表加载失败' + response.data.messge,
              type: 'warning'
            })
          }
        })
        .catch(() => {
          self.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
    },
    optionalTransferChange(value, direction, movedKeys) {
      const self = this
      const obj = []
      self.completion.requiredItems.forEach(item => {
        value.forEach(key => {
          if (item === key) {
            obj.push(item)
          }
        })
      })
      if (obj && typeof obj !== 'undefined') {
        obj.forEach(key => {
          if (self.completion.optionalItems) {
            const len = self.completion.optionalItems.length
            for (var i = 0; i < len; i++) {
              if (key === self.completion.optionalItems[i]) {
                self.completion.optionalItems.splice(i, 1)
              }
            }
          }
        })
        let data = ''
        self.transferData.forEach(item => {
          obj.forEach(key => {
            if (item.key === key) {
              data += item.label + '、'
            }
          })
        })
        if (data && typeof data !== 'undefined') {
          self.$message.info(
            '必填项中已存在（' + data.substr(0, data.length - 1) + '）！'
          )
        }
      }
    },
    requiredTransferChange(value, direction, movedKeys) {
      const self = this
      const obj = []
      self.completion.optionalItems.forEach(item => {
        value.forEach(key => {
          if (item === key) {
            obj.push(item)
          }
        })
      })
      if (obj && typeof obj !== 'undefined') {
        obj.forEach(key => {
          if (self.completion.requiredItems) {
            const len = self.completion.requiredItems.length
            for (var i = 0; i < len; i++) {
              if (key === self.completion.requiredItems[i]) {
                self.completion.requiredItems.splice(i, 1)
              }
            }
          }
        })
        let data = ''
        self.transferData.forEach(item => {
          obj.forEach(key => {
            if (item.key === key) {
              data += item.label + '、'
            }
          })
        })
        if (data && typeof data !== 'undefined') {
          self.$message.info(
            '选填项中已存在（' + data.substr(0, data.length - 1) + '）！'
          )
        }
      }
    },
    getCompletion() {
      const self = this
      getCompletion({ completionId: self.completionId })
        .then(response => {
          if (response.data.status === 'success') {
            self.initCompletion(response.data.data)
          } else {
            self.$message({
              message: '完工项目加载失败' + response.data.messge,
              type: 'warning'
            })
          }
        })
        .catch(() => {
          self.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
    },
    addRow() {
      const self = this
      self.completionFormVisible = true
      self.fromTitle = '新增工单完工'
      self.clearCompletion()
      self.loadCompletionCol()
    },
    editRow(index, rows) {
      const self = this
      self.completionFormVisible = true
      self.fromTitle = '修改工单完工'
      self.completionId = rows.completionConfigId
      self.getCompletion()
      self.loadCompletionCol()
      // rows.splice(index, 1);
    },
    deleteRow(index, rows) {
      const self = this
      self.completionId = rows.completionConfigId
      removeCompletion({ completionId: self.completionId })
        .then(response => {
          if (response.data.status === 'success') {
            self.loadTableData()
            self.$message({
              message: '删除完工项目成功',
              type: 'success'
            })
          } else {
            self.$message({
              message: '删除完工项目失败' + response.data.messge,
              type: 'warning'
            })
          }
        })
        .catch(() => {
          self.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
    },
    submitForm() {
      const self = this
      if (!self.completion.partnerId) {
        self.$message.info('合作商信息不能为空，请刷新页面重试！')
        return
      }
      if (!self.completion.photoNumber) {
        self.$message.info('图片数量不能为空！')
        return
      }
      if (!self.completion.photoDesc) {
        self.$message.info('图片描述不能为空！')
        return
      }
      let items = []
      if (self.completion.optionalItems && self.completion.optionalItems.length > 0) {
        items = items.concat(self.completion.optionalItems)
      }
      if (self.completion.requiredItems && self.completion.requiredItems.length > 0) {
        items = items.concat(self.completion.requiredItems)
      }
      if (items && items.length > 0) {
        if (items.includes('inGuaranteePeriod') && items.includes('specificationId') && items.includes('serviceMeasures')) {
          if (
            (self.completion.optionalItems &&
              self.completion.optionalItems.length > 0) ||
            (self.completion.requiredItems &&
              self.completion.requiredItems.length > 0)
          ) {
            saveCompletion(self.completion)
              .then(response => {
                if (response.data.status === 'success') {
                  self.loadTableData()
                  self.completionFormVisible = false
                  self.$message({
                    message: '保存完工项目成功',
                    type: 'success'
                  })
                } else {
                  self.$message({
                    message: '保存完工项目失败' + response.data.messge,
                    type: 'warning'
                  })
                }
              })
              .catch(() => {
                self.$message({
                  type: 'info',
                  message: '网络请求失败'
                })
              })
          } else {
            self.$message.info('必填项和选填项不能同时为空！')
          }
        } else {
          self.$message.info('质保期、规格、处理措施为必选项！')
        }
      }
    },
    initCompletion(data) {
      const self = this
      self.completion = {
        completionId: data.completionId,
        partnerId: data.partnerId,
        orderServiceType: data.orderServiceType ? data.orderServiceType : [],
        category: data.category ? data.category : [],
        optionalItems: data.optionalItems ? data.optionalItems : [],
        requiredItems: data.requiredItems ? data.requiredItems : [],
        photoNumber: data.photoNumber,
        photoDesc: data.photoDesc
      }
    },
    clearCompletion() {
      const self = this
      self.completion = {
        completionId: '',
        partnerId: self.query.partnerId,
        orderServiceType: [],
        category: [],
        optionalItems: [],
        requiredItems: [],
        photoNumber: 0,
        photoDesc: ''
      }
    }
  }
}
</script>
